package com.yuexun.dhdoctor.module.commun.ui;

import android.content.Intent;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.TextView;


import com.yuexun.dhdoctor.R;
import com.yuexun.dhdoctor.base.AppContext;
import com.yuexun.dhdoctor.base.BaseEntity;
import com.yuexun.dhdoctor.base.BaseKJActivity;
import com.yuexun.dhdoctor.config.AppConfig;
import com.yuexun.dhdoctor.config.DbConfig;
import com.yuexun.dhdoctor.module.Contract.adapter.CreateGroupAdapter;
import com.yuexun.dhdoctor.module.Contract.bean.DepartOrPeopleData;
import com.yuexun.dhdoctor.module.Contract.bean.GroupGroupBean;
import com.yuexun.dhdoctor.module.Contract.bean.GroupGroupData;
import com.yuexun.dhdoctor.module.Contract.model.impl.GroupModel;
import com.yuexun.dhdoctor.module.Contract.presenter.impl.GroupPresenter;
import com.yuexun.dhdoctor.module.Contract.ui.view.IGroupView;
import com.yuexun.dhdoctor.module.commun.adapter.GroupExpandableCheckAdapter;
import com.yuexun.dhdoctor.widget.EmptyLayout;

import org.kymjs.kjframe.KJDB;
import org.kymjs.kjframe.ui.ViewInject;
import org.kymjs.kjframe.utils.KJLoger;
import org.kymjs.kjframe.utils.PreferenceHelper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Administrator on 2018/8/9 0009.
 */

public class Act_Group extends BaseKJActivity implements IGroupView {
    @Bind(R.id.title_tv)
    TextView titleTv;
    @Bind(R.id.group_lit)
    ExpandableListView groupLit;
    @Bind(R.id.empty_layout)
    EmptyLayout emptyLayout;
    @Bind(R.id.grid)
    GridView grid;
    @Bind(R.id.addmember_sure_btn)
    TextView addmemberSureBtn;

    private GroupPresenter presenter;
    private List<GroupGroupData> publicgroupGroupDataBeans = new ArrayList<>();
    private List<GroupGroupData> groupGroupDataBeans = new ArrayList<>();
    private List<GroupGroupBean> groupGroupBeen = new ArrayList<>();
    //    private BaseAdapter adapter;
    private GroupExpandableCheckAdapter adapter;
    CreateGroupAdapter createGroupAdapter;

    //2:公共群组
    private String groupType = "2";
    //0：不能选择自己  1：能选择
    private int isSelectMe;
    //0:单选  1：多选
    private int type;

    private Handler handler;
    KJDB kjdb;

    ArrayList<GroupGroupData> selectValues =new ArrayList<>();

    @Override
    public void setRootView() {
        super.setRootView();
        setContentView(R.layout.act_group);
        ButterKnife.bind(this);
    }




    @Override
    public void initData() {
        titleTv.setText("群组处理");
        isSelectMe = getIntent().getExtras().getInt("isSelectMe", 0);
        type = getIntent().getExtras().getInt("type");
        presenter = new GroupPresenter(new GroupModel(), this);
        selectValues = (ArrayList<GroupGroupData>) getIntent().getExtras().getSerializable("group");
        initHandle();
        initView();
        setGridView();

        kjdb = KJDB.create(this, DbConfig.DBNAME, DbConfig.ISDEBUG, DbConfig.DBVERSION, new KJDB.DbUpdateListener() {
            @Override
            public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
                if(newVersion>oldVersion)
                {
                    Cursor cursor = db.rawQuery(
                            "SELECT name FROM sqlite_master WHERE type ='table'", null);
                    if (cursor != null) {
                        while (cursor.moveToNext()) {
                            // 添加异常捕获.忽略删除所有表时出现的异常:
                            // table sqlite_sequence may not be dropped
                            try {
                                db.execSQL("DROP TABLE " + cursor.getString(0));
                            } catch (SQLException e) {
                                KJLoger.debug(getClass().getName() + e.getMessage());
                            }
                        }
                    }
                    if (cursor != null) {
                        cursor.close();
                        cursor = null;
                    }
                }
            }
        });
        new Thread(new Runnable() {
            @Override
            public void run() {
                groupGroupBeen.clear();
                groupType = "2";
                Map<String, String> params = new HashMap<>();
                params.put("sessionUuid", PreferenceHelper.readString(AppContext.getInstance(), AppConfig.USER_INFO, AppConfig.SESSION_ID));
                params.put("groupType", groupType);
                presenter.getGroupDatas(params);
            }
        }).start();
    }


    void initView() {
        adapter = new GroupExpandableCheckAdapter(aty, groupGroupBeen,selectValues,handler,isSelectMe,type,true);
        groupLit.setAdapter(adapter);
        groupLit.setGroupIndicator(null);
        groupLit.setDivider(null);

        emptyLayout.setOnLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                emptyLayout.setErrorType(EmptyLayout.NETWORK_LOADING);
            }
        });

//        deptList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//            @Override
//            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                ChildDepartmentsBean childDepartmentsBean = (ChildDepartmentsBean) parent.getItemAtPosition(position);
//                datas = (ArrayList<GroupDataBean>) kjdb.findAllByWhere(GroupDataBean.class,
//                        "department_id = " + childDepartmentsBean.getDepartment_id());
//                if (datas != null && datas.size() > 0) {
//                    refresh(datas);
//                } else {
//                    Map<String, String> params = new HashMap<>();
//                    params.put("sessionUuid", PreferenceHelper.readString(aty, AppConfig.USER_INFO, AppConfig.SESSION_ID));
//                    params.put("parentDepartmentId", childDepartmentsBean.getDepartment_id() + "");
//                    presenter.getGroupDatas(params);
//                }
//            }
//        });

    }

    void initHandle() {
        handler = new Handler() {

            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
//                    case 10001: // 搜索有文字的的时候
//                        btnSearchClear.setVisibility(View.VISIBLE);
//                        break;
//                    case 10002: // 搜索没文字的的时候
//                        btnSearchClear.setVisibility(View.INVISIBLE);
//                        break;
                    case 10003:
                        setGridView();
                        break;
                    case 0x01:
//                        initLoad();
                        break;
                    default: // 默认消息处理

                        break;
                }
            }
        };
    }

    @Override
    public void showGroupDatas(BaseEntity<GroupGroupData> baseEntity) {
        if ("200".equals(baseEntity.getStatus())) {
            if (groupType.equals("2")) {
                if (publicgroupGroupDataBeans.size() > 0) {
                    publicgroupGroupDataBeans.clear();
                }
                publicgroupGroupDataBeans = baseEntity.getDatas();
                GroupGroupBean groupBean = new GroupGroupBean();
                groupBean.setGroup_name("公共群组");
                groupBean.setDatas(publicgroupGroupDataBeans);
                groupGroupBeen.add(groupBean);

                groupType = "1";
                Map<String, String> params = new HashMap<>();
                params.put("sessionUuid", PreferenceHelper.readString(AppContext.getInstance(), AppConfig.USER_INFO, AppConfig.SESSION_ID));
                params.put("groupType", groupType);
                presenter.getGroupDatas(params);
            } else {
                if (groupGroupDataBeans.size() > 0) {
                    groupGroupDataBeans.clear();
                }
                groupGroupDataBeans = baseEntity.getDatas();

                GroupGroupBean groupBean = new GroupGroupBean();
                groupBean.setGroup_name("个人群组");
                groupBean.setDatas(groupGroupDataBeans);
                groupGroupBeen.add(groupBean);

                adapter.setGroupGroupBeen(groupGroupBeen);
                if (groupLit != null) {
                    for (int i = 0; i < adapter.getGroupCount(); i++) {
                        groupLit.expandGroup(i);

                    }
                }
            }

        } else {
            ViewInject.toast("数组：" + baseEntity.getMessage());
        }

        if (emptyLayout != null) {
            emptyLayout.dismiss();
        }
    }


    private void setGridView() {
        int size = selectValues.size();

        List<DepartOrPeopleData> datas = new ArrayList<>();
        for (GroupGroupData groupGroupData : selectValues) {
            DepartOrPeopleData data = new DepartOrPeopleData();
            data.setDataId(groupGroupData.getGroupId() + "");
            data.setDataName(groupGroupData.getTitle());
            datas.add(data);
        }

        if (size == 0) {
            addmemberSureBtn.setBackgroundResource(R.color.doc_advice_02);
            addmemberSureBtn.setEnabled(false);
        } else {
            addmemberSureBtn.setBackgroundResource(R.color.doc_advice_01);
            addmemberSureBtn.setEnabled(true);
        }

        addmemberSureBtn.setText("确认");

        int length = 80;

        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        float density = dm.density;
        int gridviewWidth = (int) (size * (length + 4) * density);
        int itemWidth = (int) (length * density);

        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                gridviewWidth, LinearLayout.LayoutParams.FILL_PARENT);
        grid.setLayoutParams(params); // 重点
        grid.setColumnWidth(itemWidth); // 重点
        grid.setHorizontalSpacing(5); // 间距
        grid.setStretchMode(GridView.NO_STRETCH);
        grid.setNumColumns(size); // 重点

        createGroupAdapter = new CreateGroupAdapter(grid, datas, R.layout.item_send_addmember);
        grid.setAdapter(createGroupAdapter);
    }


    @OnClick({R.id.dept_back, R.id.addmember_sure_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.dept_back:
                finish();
                break;
            case R.id.addmember_sure_btn:
                Bundle bundle = new Bundle();
                Intent intent = new Intent();
                bundle.putSerializable("groups", selectValues);
                intent.putExtras(bundle);
                setResult(10002, intent);
                finish();
                break;
        }
    }
}
